package yi.wuhenbot.Service;


import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.bouncycastle.jcajce.interfaces.EdDSAKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import yi.wuhenbot.Utils.BotTokenUtil;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * Bot验证服务
 * @author wuhen
 */
@Service
public class BotService {
    @Autowired
    private BotTokenUtil botTokenUtil;

    /**
     * 处理事件
     * @param body 事件体
     */
    public void handleEvent(String body) {
        JSONObject jsonObject = JSONObject.parseObject(body);
        int op = jsonObject.getIntValue("op");
        String type = jsonObject.getString("t");
        JSONObject data = jsonObject.getJSONObject("d");

        switch (op) {
            case 0: // Dispatch
                System.out.println("事件类型: " + type);
                System.out.println("事件数据: " + data.toJSONString());
                break;
            case 1: // Heartbeat
                System.out.println("心跳包");
                break;
            case 13: // 回调地址验证
                validateCallback(data);
                break;
            default:
                System.out.println("未知的 opcode: " + op);
        }
    }
    /**
     * 验证回调
     * @param data 回调数据
     */
    private void validateCallback(JSONObject data) {
        String plainToken = data.getString("plain_token");
        String eventTs = data.getString("event_ts");
        System.out.println("回调验证: plain_token=" + plainToken + ", event_ts=" + eventTs);

        try {
            // 生成私钥
            PrivateKey privateKey = generatePrivateKey(botTokenUtil.getAppSecret());

            // 构造消息
            byte[] message = (eventTs + plainToken).getBytes();

            // 签名
            Signature signature = Signature.getInstance("Ed25519", "BC");
            signature.initSign(privateKey);
            signature.update(message);
            byte[] signatureBytes = signature.sign();

            // 转换为十六进制字符串
            String signatureHex = bytesToHex(signatureBytes);

            // 返回验证响应
            JSONObject response = new JSONObject();
            response.put("plain_token", plainToken);
            response.put("signature", signatureHex);

            System.out.println("回调验证响应: " + response.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("回调验证异常: " + e.getMessage());
        }
    }
    /**
     * 生成私钥
     * @param secret 机器人appSecret
     * @return 私钥
     * @throws Exception 异常
     */
    private PrivateKey generatePrivateKey(String secret) throws Exception {
        // 根据 Bot Secret 生成 seed
        String seed = secret;
        while (seed.getBytes().length < 32) {
            seed += seed;
        }
        if (seed.getBytes().length > 32) {
            seed = seed.substring(0, 32);
        }

        System.out.println("生成的 seed: " + seed);

        // 生成私钥
        KeyFactory keyFactory = KeyFactory.getInstance("EdDSA", "BC");
        EdDSAKey eddsaKey = (EdDSAKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(seed.getBytes()));
        System.out.println("生成的私钥: " + eddsaKey);

        return (PrivateKey) eddsaKey;
    }
    /**
     * 字节数组转十六进制字符串
     * @param bytes 字节数组
     * @return 十六进制字符串
     */
    private String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
